<template>
  <el-dialog
    v-model="dialogVisible"
    title="创建维修工单"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="社区" prop="communityId">
        <el-select v-model="formData.communityId" placeholder="请选择社区" style="width: 100%">
          <el-option v-for="item in communityList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="维修标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入维修标题" maxlength="100" show-word-limit />
      </el-form-item>
      
      <el-form-item label="维修类型" prop="repairType">
        <el-select v-model="formData.repairType" placeholder="请选择维修类型" style="width: 100%">
          <el-option label="水电维修" :value="1" />
          <el-option label="门窗维修" :value="2" />
          <el-option label="电梯维修" :value="3" />
          <el-option label="消防维修" :value="4" />
          <el-option label="其他" :value="5" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="维修地址" prop="repairAddress">
        <el-input v-model="formData.repairAddress" placeholder="请输入维修地址，如：1栋101室、社区机房、公共区域等" maxlength="200" show-word-limit />
      </el-form-item>
      
      <el-form-item label="维修描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请详细描述维修内容" maxlength="500" show-word-limit />
      </el-form-item>
      
      <el-form-item label="紧急程度" prop="urgencyLevel">
        <el-select v-model="formData.urgencyLevel" placeholder="请选择紧急程度" style="width: 100%">
          <el-option label="一般" :value="1" />
          <el-option label="紧急" :value="2" />
          <el-option label="非常紧急" :value="3" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" maxlength="50" />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input 
          v-model="formData.contactPhone" 
          placeholder="请输入手机号码" 
          maxlength="11" 
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="可填写补充说明" maxlength="500" show-word-limit />
      </el-form-item>
      
      <el-form-item label="上传图片">
        <ImageUpload
          v-model="formData.imageList"
          :upload-type="'IMAGE'"
          :upload-source="'WEB'"
          :multiple="true"
          :max-size="10"
          :allowed-types="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']"
          :limit="9"
          tip="请上传故障现场图片，支持jpg、jpeg、png、gif、bmp、webp格式，最大10MB，最多9张"
          @on-success="handleImageUploadSuccess"
          @on-error="handleImageUploadError"
          @on-remove="handleImageRemove"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">提交工单</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { repairOrderApi } from '@/api/repair'
import { commonApi } from '@/api/repair'
import { useUserStore } from '@/store/user'
import { validators } from '@/utils/validate'
import ImageUpload from '@/components/ImageUpload.vue'

const props = defineProps<{ 
  modelValue: boolean, 
  communityList: {id: number, name: string}[] 
}>()
const emit = defineEmits(['update:modelValue', 'confirm'])

const userStore = useUserStore()
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()

const formData = reactive({
  // 必填字段
  orderNo: '', // 工单编号，后端自动生成
  communityId: undefined as number | undefined,
  userId: undefined as number | undefined, // 当前用户ID
  householdId: undefined as number | undefined, // 可选，公共设施维修时可为空
  title: '',
  description: '',
  repairAddress: '',
  repairType: undefined as number | undefined,
  urgencyLevel: undefined as number | undefined,
  contactName: '',
  contactPhone: '',
  // 可选字段
  remark: '',
  imageList: [] as any[] // 图片列表
})

const formRules = {
  communityId: [ { required: true, message: '请选择社区', trigger: 'change' } ],
  title: [ { required: true, message: '请输入维修标题', trigger: 'blur' } ],
  repairType: [ { required: true, message: '请选择维修类型', trigger: 'change' } ],
  repairAddress: [ { required: true, message: '请输入维修地址', trigger: 'blur' } ],
  description: [ { required: true, message: '请输入维修描述', trigger: 'blur' }, { min: 5, max: 500, message: '描述长度5-500字', trigger: 'blur' } ],
  urgencyLevel: [ { required: true, message: '请选择紧急程度', trigger: 'change' } ],
  contactName: [ { required: true, message: '请输入联系人', trigger: 'blur' } ],
  contactPhone: [ 
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    validators.mobile('请输入正确的手机号码')
  ]
}

watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    resetForm()
  }
})

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 设置当前用户ID
    formData.userId = userStore.userInfo?.id
    
    // 处理图片列表，提取URL字符串数组（符合后端接口要求）
    const imageList = formData.imageList.map((file: any) => {
      // 提取文件URL
      const fileUrl = file.url || file.fileUrl
      if (fileUrl) {
        return fileUrl
      }
      return null
    }).filter(Boolean)
    
    const submitData = { 
      ...formData,
      imageList: imageList
    }
    
    console.log('提交工单数据:', submitData)
    emit('confirm', submitData)
  } catch (e) {
    // 校验失败
  } finally {
    submitting.value = false
  }
}

const handleReset = () => {
  resetForm()
}

const handleClose = () => {
  emit('update:modelValue', false)
}

// 从URL中提取文件名
const extractFileNameFromUrl = (url: string): string => {
  if (url) {
    const parts = url.split('/')
    return parts[parts.length - 1] || 'unknown_file'
  }
  return 'unknown_file'
}

// 图片上传成功
const handleImageUploadSuccess = (response: any, file: any, fileList: any[]) => {
  console.log('图片上传成功:', response)
  ElMessage.success('图片上传成功')
}

// 图片上传失败
const handleImageUploadError = (error: Error, file: any, fileList: any[]) => {
  console.error('图片上传失败:', error)
  ElMessage.error('图片上传失败')
}

// 图片删除
const handleImageRemove = (file: any, fileList: any[]) => {
  console.log('删除图片:', file)
  ElMessage.success('图片删除成功')
}

const resetForm = () => {
  Object.assign(formData, {
    orderNo: '',
    communityId: undefined,
    userId: undefined,
    householdId: undefined,
    title: '',
    description: '',
    repairAddress: '',
    repairType: undefined,
    urgencyLevel: undefined,
    contactName: '',
    contactPhone: '',
    remark: '',
    imageList: []
  })
  formRef.value?.clearValidate()
}
</script> 